package com.czy.owner.ui.packagecardproject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.czy.owner.R;
import com.czy.owner.adapter.StorePackageDetailAdapter;
import com.czy.owner.api.OwnerPacStoreServicePackageInfoApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.MyServicePackageItemList;
import com.czy.owner.entity.StorePackageDetailModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.DecimalUtil;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.TimeUtils;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.widget.FullyLinearLayoutManager;
import com.czy.owner.widget.MyRecyclerView;
import com.czy.owner.widget.UniversalDialog;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by wangyang on 2016/12/15 0015.
 * 门店套餐详细
 */
public class PackageCardDetailActivity extends BaseActivity /*implements MyScrollView.ScrollViewLine*/ {
    //    @ViewInject(R.id.myscrollview)
//    private MyScrollView myScrollView;
//    @ViewInject(R.id.line_headview)
//    private LinearLayout lineHeadView;
    @BindView(R.id.img_package_card_bg)
    ImageView imgPackageCardBg;
    @BindView(R.id.tv_package_card_name)
    TextView tvPackageCardName;
    @BindView(R.id.tv_used_time)
    TextView tvUserTime;
    @BindView(R.id.tv_package_note)
    TextView tvPackageNote;
    //商品
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;
    @BindView(R.id.rv_package_detail_goods)
    MyRecyclerView rvPackageDetailGoods;
    @BindView(R.id.tv_package_goods_head_title)
    TextView tvPackageGoodsHeadTitle;
    @BindView(R.id.tv_package_goods_head_money)
    TextView tvPackageGoodsHeadMoney;
    //服务
    @BindView(R.id.ll_service)
    LinearLayout llService;
    @BindView(R.id.rv_package_detail_service)
    MyRecyclerView rvPackageDetailService;
    @BindView(R.id.tv_package_service_head_title)
    TextView tvPackageServiceHeadTitle;
    @BindView(R.id.tv_package_service_head_money)
    TextView tvPackageServiceHeadMoney;
    //2018-2-27wangyang新增
    @BindView(R.id.ll_package_price)
    LinearLayout llPackagePrice;
    @BindView(R.id.tv_give_amount)
    TextView tvGiveAmount;
    @BindView(R.id.tv_old_price)
    TextView tvOldPrice;
    @BindView(R.id.tv_now_price)
    TextView tvNowPrice;
    @BindView(R.id.relat_goods_head)
    RelativeLayout relatGoodsHead;
    @BindView(R.id.relat_service_head)
    RelativeLayout relatServiceHead;

    @BindView(R.id.tv_bottom_old_price)
    TextView tvBottomOldPrice;
    @BindView(R.id.tv_bottom_now_price)
    TextView tvBottomNowPrice;

    private int servicePackageId = 0;
    private int storeId;

    private double priceGood = 0.00;
    private double priceService = 0.00;
    private double totalPrice = 0.00;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_package_card_detail;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.my_package_card_detail);
        servicePackageId = getIntent().getIntExtra("servicePackageId", 0);
        RxBus.getDefault().register(this);
        tvOldPrice.setVisibility(View.GONE);
        tvNowPrice.setVisibility(View.GONE);
        getDataList();
    }

    @Override
    protected void updateViews() {

    }

    private void getDataList() {
        OwnerPacStoreServicePackageInfoApi ownerPacMyInfoApi = new OwnerPacStoreServicePackageInfoApi(new HttpOnNextListener<StorePackageDetailModel>() {
            @Override
            public void onNext(StorePackageDetailModel model) {
                setDataList(model);
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if (e.getMessage().equals("套餐已不存在或者过期！")) {
                    finish();
                }
            }
        }, this);
        ownerPacMyInfoApi.setSession(UserHelper.getInstance().getSessionInfoModel(PackageCardDetailActivity.this).getSession());
        ownerPacMyInfoApi.setStoreId(SharedPreferencesUtils.getParam(PackageCardDetailActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        ownerPacMyInfoApi.setServicePackageId(servicePackageId + "");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(ownerPacMyInfoApi);
    }


    private void setDataList(StorePackageDetailModel model) {
        if (TextUtils.isEmpty(model.getLogo()) || model.getLogo().equals(" ")) {
            imgPackageCardBg.setVisibility(View.GONE);
        } else {
            GlideUtils.loadImage(PackageCardDetailActivity.this, model.getLogo(), imgPackageCardBg, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                @Override
                public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

                }

                @Override
                public void onLoadingError(String source, Exception e) {

                }
            }, R.mipmap.default_banner, R.mipmap.default_banner);
        }
        tvPackageCardName.setText(model.getPackageName());
//        String strNowPrice = "现价 <font color='#f4a624'>" + "￥" + String.format("%.2f", model.getPrice()) + "</font>";
//        tvNowPrice.setText(Html.fromHtml(strNowPrice));
//        tvOldPrice.setText("原价￥" + String.format("%.2f", model.getOriginalPrice()));
        if(!TextUtils.isEmpty(model.getNote())){
            tvPackageNote.setVisibility(View.VISIBLE);
            tvPackageNote.setText(model.getNote());
        }else {
            tvPackageNote.setVisibility(View.GONE);
        }

       //2018-2-27 wangyang 修改
        tvBottomOldPrice.setText("原价￥" + String.format("%.2f", model.getOriginalPrice()));
        tvBottomOldPrice.setPaintFlags(Paint. STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
        tvBottomNowPrice.setText("现价￥" + String.format("%.2f", model.getPrice()));



        if (model.getGiveAmount() > 0) {
            llPackagePrice.setVisibility(View.VISIBLE);
            tvGiveAmount.setVisibility(View.VISIBLE);
            tvGiveAmount.setText("赠送余额: ¥" + DecimalUtil.formatNum(model.getGiveAmount() + ""));

        } else {
            llPackagePrice.setVisibility(View.GONE);
            tvGiveAmount.setVisibility(View.INVISIBLE);

        }

        int validityType = model.getValidityType();//0>>>永久有效;1>>>固定时长;2>>>固定时间
        int fixTimeType = model.getFixTimeType();//0>>>>>月;1>>>>年

        if (validityType == 0) {
            tvUserTime.setText("有效期: 永久有效");
        } else if (validityType == 1) {
            if (fixTimeType == 0) {
                tvUserTime.setText("有效期: " + model.getFixTimeValue() + "个月");
            } else if (fixTimeType == 1) {
                tvUserTime.setText("有效期: " + model.getFixTimeValue() + "年");
            }
        } else if (validityType == 2) {
            tvUserTime.setText("有效期: " + TimeUtils.formatTimeDifference4(model.getStartTime()) + "至" + TimeUtils.formatTimeDifference4(model.getEndTime()));
        }


        storeId = model.getStoreId();
        totalPrice = model.getPrice();

        List<MyServicePackageItemList> goodsList = new ArrayList<>();
        List<MyServicePackageItemList> serviceList = new ArrayList<>();


        if (model.getGoodsList().size() > 0) {
            for (int i = 0; i < model.getGoodsList().size(); i++) {
                String itemName = model.getGoodsList().get(i).getItemName();
                double price = model.getGoodsList().get(i).getPrice();
                int count = model.getGoodsList().get(i).getCount();
                String logo = model.getGoodsList().get(i).getLogo();
                String specValue = model.getGoodsList().get(i).getSpecValue();
                boolean unlimitedCount = model.getGoodsList().get(i).isUnlimitedCount();
                goodsList.add(new MyServicePackageItemList(itemName, price, count, logo, specValue, unlimitedCount));
            }

        }


        if (model.getServiceList().size() > 0) {
            for (int i = 0; i < model.getServiceList().size(); i++) {
                String itemName = model.getServiceList().get(i).getItemName();
                double price = model.getServiceList().get(i).getPrice();
                int count = model.getServiceList().get(i).getCount();
                String logo = model.getServiceList().get(i).getLogo();
                String specValue = model.getServiceList().get(i).getSpecValue();
                boolean unlimitedCount = model.getServiceList().get(i).isUnlimitedCount();

                serviceList.add(new MyServicePackageItemList(itemName, price, count, logo, specValue, unlimitedCount));
            }
        }


        if (goodsList != null && goodsList.size() > 0) {
            FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(PackageCardDetailActivity.this);
            rvPackageDetailGoods.setLayoutManager(layoutManager);
            rvPackageDetailGoods.addItemDecoration(new RecycleViewDivider(PackageCardDetailActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
            rvPackageDetailGoods.setAdapter(new StorePackageDetailAdapter(PackageCardDetailActivity.this, goodsList, false));
            for (int i = 0; i < goodsList.size(); i++) {
                priceGood = goodsList.get(i).getPrice() * goodsList.get(i).getCount() + priceGood;
            }
//            tvPackageGoodsHeadTitle.setText("商品项目" + "(" + goodsList.size() + "件" + ")");
            tvPackageGoodsHeadTitle.setText("商品项目");
//            tvPackageGoodsHeadMoney.setText("小计: ￥" + String.format("%.2f", priceGood));
            tvPackageGoodsHeadMoney.setText("");
        } else {
            llGoods.setVisibility(View.GONE);
        }


        if (serviceList != null && serviceList.size() > 0) {
            FullyLinearLayoutManager layoutManager = new FullyLinearLayoutManager(PackageCardDetailActivity.this);
            rvPackageDetailService.setLayoutManager(layoutManager);
            rvPackageDetailService.addItemDecoration(new RecycleViewDivider(PackageCardDetailActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
            rvPackageDetailService.setAdapter(new StorePackageDetailAdapter(PackageCardDetailActivity.this, serviceList, false));

            for (int i = 0; i < serviceList.size(); i++) {
                priceService = serviceList.get(i).getPrice() * serviceList.get(i).getCount() + priceService;

            }
//            tvPackageServiceHeadTitle.setText("服务项目" + "(" + serviceList.size() + "件" + ")");
            tvPackageServiceHeadTitle.setText("服务项目");
//            tvPackageServiceHeadMoney.setText("小计: ￥" + String.format("%.2f", priceService));
            tvPackageServiceHeadMoney.setText("");
        } else {
            llService.setVisibility(View.GONE);
        }
    }


    @OnClick(R.id.btn_store_package)
    public void btnStorePackage(View view) {
        if (totalPrice == 0.00) {
            MyLog.e("yang", "0元套餐购买");
            helpDialog("温馨提示", "是否进行购买套餐", "确定", "取消");
        } else {
            Intent ti = new Intent(PackageCardDetailActivity.this, BuyStorePackageActivity.class);
            ti.putExtra("totalPrice", totalPrice);
            ti.putExtra("servicePackageId", servicePackageId + "");
            ti.putExtra("storeId", storeId);
            startActivity(ti);
        }


    }


    @Subscribe(code = Constants.BUY_PACKAGE_SUCCESS_CODE, threadMode = ThreadMode.MAIN)
    public void eventBuyPackage(CommonEvent bugPackageEvent) {
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);

    }


    protected void setTitleLayout(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int statusBarHeight = getStatusBarHeight(PackageCardDetailActivity.this.getBaseContext());
            view.setPadding(0, statusBarHeight, 0, 0);
        }
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    private void payDepositAmount() {
        mLoadView.ShowLoadView();
        String url = Constants.APP_API_BASE + Constants.OWN_ORDER_BUYPACKAGE;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(PackageCardDetailActivity.this).getSession());
        params.addBodyParameter("storeId", storeId + "");
        params.addBodyParameter("useStoreBalance", "true");
        params.addBodyParameter("servicePackageId", servicePackageId + "");
        params.addBodyParameter("numbers", "1");
//        params.addBodyParameter("pushPackageId", pushPackageId + "");
        MyLog.e("yang", "params==" + params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "套餐付款onSuccess==" + result);
                String data = PhoneUtils.checkResponseFlag(PackageCardDetailActivity.this, result);
                if (data != null) {
                    if (data.equals("")) {
                        RxBus.getDefault().post(Constants.BUY_PACKAGE_SUCCESS_CODE, new CommonEvent("购买套餐"));
                        PhoneUtils.ShowToastMessage(PackageCardDetailActivity.this, "购买该套餐成功");
                    }

                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "套餐付款onError==" + ex.toString());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mLoadView.CancleLoadView();
            }
        });
    }


//    @Override
//    public void onScrollChanged(int l, int t, int oldl, int oldt) {
//        if (oldt < 10) {
//            lineHeadView.getBackground().setAlpha(0);
//        } else if (oldt < 40 && oldt > 10) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 8));
//        } else if (oldt < 70 && oldt > 40) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 7));
//        } else if (oldt < 100 && oldt > 70) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 6));
//        } else if (oldt < 130 && oldt > 100) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 5));
//        } else if (oldt < 150 && oldt > 130) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 4));
//        } else if (oldt < 180 && oldt > 150) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 3));
//        } else if (oldt < 200 && oldt > 180) {
//            lineHeadView.getBackground().setAlpha((int) (oldt / 2));
//        } else if (oldt >= 200) {
//            lineHeadView.getBackground().setAlpha(255);
//        }
//    }

    private void helpDialog(String title, String msg, String sure, String cancle) {
        new UniversalDialog(PackageCardDetailActivity.this).builder()
                .setTitle(title)
                .setMsg(msg)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        payDepositAmount();
                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
